import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { _HttpClient } from '@delon/theme';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SimpleList } from '@api/simple/model/simpleList.model';
import { SysKeyValueService } from '@api/sys/service/sysKeyValue.service';
import { SysKeyValue } from '@api/sys/model/sysKeyValue.model';
import { SimpleListFormFields } from '@api/simple/model/simpleListFormFields.model';
import { SimpleSql } from '@api/simple/model/simpleSql.model';
import { SimpleSqlService } from '@api/simple/service/simpleSql.service';
import { BehaviorSubject, Observable } from 'rxjs';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';
import { QueryBody } from '@api/model/queryBody.model';
import { SimpleActionField } from '@api/simple/model/simpleActionField.model';
import { SimpleActionService } from '@api/simple/service/simpleAction.service';

@Component({
  selector: 'app-simple-list-edit-base',
  templateUrl: './base.component.html',
})
export class SimpleListEditBaseComponent implements OnInit {
  _data: SimpleListFormFields = {};

  @Input()
  set data(data: SimpleListFormFields) {
    if (data.action) {
      data.action!.fields.forEach((action) => this.selectedActions.push(action.code!));
    }

    this._data = data;
  }

  get data() {
    return this._data;
  }

  @Input()
  isAdd: boolean = false;

  @ViewChild('f', { static: false })
  public form!: FormGroup;
  record: SimpleList = {};
  i: any;
  datasourceTypes: SysKeyValue[] = [];
  sqlList: SimpleSql[] = [];
  sqlLoading = true;
  searchChange$ = new BehaviorSubject('');

  actions: SimpleActionField[] = [];

  selectedActions: string[] = [];

  constructor(
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    protected route: ActivatedRoute,
    private fb: FormBuilder,
    private keyValueSerivice: SysKeyValueService,
    private simpleSqlService: SimpleSqlService,
    private simpleActionService: SimpleActionService,
  ) {}

  ngOnInit(): void {
    this.keyValueSerivice.findByParentKeyPath('/SIMPLE/DATASOURCE_TYPE').subscribe((res) => (this.datasourceTypes = res));
    this.simpleActionService.findSimpleActionFieldsByCode('list_action_template').subscribe((res) => (this.actions = res.fields));

    const getRandomNameList = (name: string): Observable<any> => this.simpleSqlService.findByQueryParams({ name: name });
    const optionList$: Observable<QueryBody<SimpleSql>> = this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .pipe(switchMap(getRandomNameList));
    optionList$.subscribe((data) => {
      this.sqlList = data.list!;
      this.sqlLoading = false;
    });
  }

  validate() {
    this.data.action!.fields = [];
    this.selectedActions.forEach((item) => {
      const action = this.actions.find((a) => item == a.code);
      this.data.action!.fields.push(action!);
    });

    Object.values(this.form.controls).forEach((control) => {
      if (control.invalid) {
        control.markAsDirty();
        control.updateValueAndValidity({ onlySelf: true });
      }
    });
  }

  sqlOnSearch(value: string) {
    this.sqlLoading = true;
    this.searchChange$.next(value);
  }

  codeChange() {
    this.data.action!.code = `${this.data.code}_list_action`;
    this.data.form!.code = `${this.data.code}_list_form`;
  }

  nameChange() {
    this.data.action!.name = `${this.data.name}工具栏`;
    this.data.form!.name = `${this.data.name}查询表单`;
  }
}
